package com.example.utils;


import com.example.system.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Configuration
public class LoginInterceptor implements WebMvcConfigurer {

    final static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);


    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return  new SecurityInterceptor();
    }
    private class SecurityInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request,
                HttpServletResponse response, Object handler)
                    throws IOException, ServletException {

            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            //判断是否已有该用户登录的session
            if(user !=null){
                return  true;
            }else {
                logger.info("用户没有登录,跳转至登陆页面!");
                String basePath = request.getContextPath();  // cms ContextPath 每次
                String path = request.getServletPath();      // 当前请求位置
                String url = request.getRequestURI();

                logger.info("ContextPath-->"+basePath);
                logger.info("当前请求路径:path-->"+path);
                logger.info("当前请求url-->"+url);

                request.setAttribute("msg","用户未登录!请重新登录!");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
             //   response.sendRedirect(basePath+"/login.jsp");
                return false;
            }
        }
    }
    @Override
    public  void addInterceptors(InterceptorRegistry registry){
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
        //排除配置
        addInterceptor.excludePathPatterns("/login","/index/**","/css/**","/images/**","/js/**",
                "/login.jsp","/valicode","/test/**","**/login.html","/test");
        //拦截配置
      //  addInterceptor.addPathPatterns("/**");
    }
}